<template>
  <VisitNav :show="1" @addVisit="addVisit"></VisitNav>
  <view class="addVisit-container">
    <scroll-view scroll-y>
      <view class="addVisit-wrapper">
        <view class="addVisit-firstrow">
          <view class="addVisit-firstrow-box">
            <text class="name-tag">姓名：</text>
            <text class="addVisit-text">{{ visitStore.patient?.name }}</text>
          </view>
          <view class="addVisit-firstrow-box">
            <text class="name-tag">性别：</text>
            <text class="addVisit-text">{{ visitStore.patient?.sex }}</text>
          </view>
          <view class="addVisit-firstrow-box">
            <text class="name-tag">年龄：</text>
            <text class="addVisit-text">{{ visitStore.patient?.age }}岁</text>
          </view>
          <view class="addVisit-firstrow-box">
            <text class="name-tag addVisit-active">随访日期：</text>
            <button
              style="
                height: 20rpx;
                text-align: center;
                display: flex;
                justify-content: center;
                align-items: center;
                border: 0.5rpx solid #61666d;
              "
              @click="showDateStyler = true"
            >
              {{ dateInitValue || '选择日期' }}
            </button>
          </view>
          <lekeDatetimeStyler
            :value="dateInitValue"
            :visible="showDateStyler"
            :model="model"
            @cancel="handCancel"
            @confirm="handConfirm"
          ></lekeDatetimeStyler>
          <view
            class="addVisit-firstrow-box"
            style="display: flex; justify-content: center; align-items: center; position: relative"
          >
            <text class="name-tag addVisit-active">随访方式：</text>
            <view class="visit-way" @tap="changeShow">
              <view class="visit-way-text">{{ visitWay[selectWayIndex] }}</view>
              <view class="visit-way-after"></view>
            </view>
            <view class="visit-way-list" v-if="showSelectWay">
              <view
                :class="selectWayIndex != index ? 'visit-way-item' : 'visit-way-item-active'"
                v-for="(way, index) in visitWay"
                :key="index"
                @tap="chageVisitWay(index)"
                >{{ way }}</view
              >
            </view>
          </view>
        </view>
        <view class="addVisit-crowdName-box">
          <text class="name-tag">人群分类：</text>
          <text
            class="addVisit-crowdName-item"
            v-for="(disease, index) in crowdNameList"
            :key="index"
            >{{ disease }}</text
          >
        </view>

        <view class="h-text">症状</view>
        <view class="addVisit-secondrow">
          <view class="checkbox-item">
            <label><checkbox :checked="symptomSet.length == 0" disabled />无症状</label>
          </view>
          <view class="checkbox-item" v-for="(symptom, index) in symptomList" :key="index">
            <label @tap="selectCheckbox(symptom)">
              <checkbox
                :value="symptom"
                :checked="symptomSet.includes(symptom)"
                @tap="selectCheckbox(symptom)"
              />{{ symptom }}
            </label>
          </view>
        </view>

        <uni-forms ref="formRef" :rules="addVisitRules" :modelValue="addVisitFrom">
          <view class="h-text">体征</view>
          <view class="addVisit-thridrow">
            <view class="addVisit-thridrow-box">
              <uni-forms-item name="bloodPressure" class="forms-error"> </uni-forms-item>
              <text class="name-tag addVisit-active">血压：</text>
              <input
                class="addvisit-input"
                type="number"
                placeholder="收缩压/舒张压"
                v-model="addVisitFrom.bloodPressure"
              />
              <text class="name-tag">mmHg</text>
            </view>

            <view class="addVisit-thridrow-box">
              <uni-forms-item name="pulseRate" class="forms-error"> </uni-forms-item>
              <text class="name-tag addVisit-active">脉率：</text>
              <input class="addvisit-input" type="number" v-model="addVisitFrom.pulseRate" />
              <text class="name-tag">次/分钟</text>
            </view>
            <view class="addVisit-thridrow-box">
              <uni-forms-item name="height" class="forms-error"> </uni-forms-item>
              <text class="name-tag addVisit-active">身高：</text>
              <input class="addvisit-input" type="number" v-model="addVisitFrom.height" />
              <text class="name-tag">cm</text>
            </view>
            <view class="addVisit-thridrow-box">
              <uni-forms-item name="weight" class="forms-error"> </uni-forms-item>
              <text class="name-tag addVisit-active">体重：</text>
              <input class="addvisit-input" type="number" v-model="addVisitFrom.weight" />
              <text class="name-tag">kg</text>
            </view>
            <view class="addVisit-thridrow-box">
              <uni-forms-item name="temperature" class="forms-error"> </uni-forms-item>
              <text class="name-tag addVisit-active">体温：</text>
              <input class="addvisit-input" type="number" v-model="addVisitFrom.temperature" />
              <text class="name-tag">摄氏度</text>
            </view>
            <view class="addVisit-thridrow-box">
              <uni-forms-item name="bloodGlucose" class="forms-error"> </uni-forms-item>
              <text class="name-tag addVisit-active">血糖：</text>
              <input class="addvisit-input" type="number" v-model="addVisitFrom.bloodGlucose" />
              <text class="name-tag">mg/dL</text>
            </view>
            <view class="addVisit-thridrow-box">
              <uni-forms-item name="result" class="forms-error"> </uni-forms-item>
              <text class="name-tag addVisit-active">体检结果：</text>
              <input class="addvisit-input" type="text" v-model="addVisitFrom.result" />
            </view>
          </view>
          <view class="h-text">用药情况及生活方式</view>
          <view class="addVisit-frouthrow">
            <view class="addVisit-frouthrow-box">
              <uni-forms-item name="drugUsage" class="forms-error"> </uni-forms-item>
              <text class="name-tag addVisit-active">用药情况：</text>
              <input
                class="addvisit-input"
                type="text"
                v-model="addVisitFrom.drugUsage"
                style="width: 250rpx"
              />
            </view>
            <view class="addVisit-frouthrow-box">
              <uni-forms-item name="livingHabit" class="forms-error"> </uni-forms-item>
              <text class="name-tag addVisit-active">生活情况：</text>
              <input
                class="addvisit-input"
                type="text"
                v-model="addVisitFrom.livingHabit"
                style="width: 250rpx"
              />
            </view>
            <view class="addVisit-frouthrow-box">
              <uni-forms-item name="remark" class="forms-error"> </uni-forms-item>
              <text class="name-tag addVisit-active">其它备注：</text>
              <input
                class="addvisit-input"
                type="text"
                v-model="addVisitFrom.remark"
                style="width: 250rpx"
              />
            </view>
          </view>
        </uni-forms>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import VisitNav from './VisitNav.vue'
import { onMounted, ref, watch } from 'vue'
import { onLoad, onShow, onTabItemTap } from '@dcloudio/uni-app'
import { http } from '@/utils/http'
import { useVisitStore } from '@/stores/modules/visit'
import lekeDatetimeStyler from '@/components/leke-datetime-styler/leke-datetime-styler.vue'
const showDateStyler = ref(false)
const dateInitValue = ref<string | number | Date>('')
const model = ['year', 'month', 'day', 'hour', 'minute', 'second']

// 确认选择回调
const handConfirm = (e: string | number | Date): void => {
  showDateStyler.value = false
  dateInitValue.value = e
  console.log('回调时间===>', e)
}

// 取消选择回调
const handCancel = (): void => {
  showDateStyler.value = false
  console.log('取消===>')
}

const visitStore = useVisitStore()
//患者分类
const crowdNameList = ref<Array<string>>()
//患者症状
const symptomList = ref<Array<string>>()
//当前时间
const curruentTime = ref('')

const visitWay = ['家访', '视频']
const selectWayIndex = ref(0)
const showSelectWay = ref(false)

//随访表单
const addVisitFrom = ref({
  doctorId: '', //医生id
  patientId: '', //患者id
  drugUsage: '', //用药情况
  symptoms: '', //患者症状
  visitTime: '', //随访时间
  visitWay: '', //随访方式
  livingHabit: '', //生活情况
  visitSign: '', //随访标志,0代表草稿箱,1代表未完成,2代表已完成，3代表随访超时
  remark: '', //随访备注
  healthTime: '', //体检时间
  result: '', //体检结果
  bloodPressure: '', //血压
  pulseRate: '', //脉率
  height: '', //身高
  weight: '', //体重
  temperature: '', //体温
  bloodGlucose: '', //血糖
})

//校验规则
const formRef = ref<UniHelper.UniFormsInstance>()
const addVisitRules: UniHelper.UniFormsRules = {
  bloodPressure: {
    rules: [{ required: true, errorMessage: '请输入血压' }],
  },
  pulseRate: {
    rules: [{ required: true, errorMessage: '请输入脉率' }],
  },
  height: {
    rules: [{ required: true, errorMessage: '请输入身高' }],
  },
  weight: {
    rules: [{ required: true, errorMessage: '请输入体重' }],
  },
  temperature: {
    rules: [{ required: true, errorMessage: '请输入体温' }],
  },
  bloodGlucose: {
    rules: [{ required: true, errorMessage: '请输入血糖' }],
  },
  drugUsage: {
    rules: [{ required: true, errorMessage: '请输入用药情况' }],
  },
  livingHabit: {
    rules: [{ required: true, errorMessage: '请输入生活情况' }],
  },
  remark: {
    rules: [{ required: true, errorMessage: '请输入随访备注' }],
  },
  result: {
    rules: [{ required: true, errorMessage: '请输入体检结果' }],
  },
}

//提交表单
const addVisit = async (visitSign: number) => {
  if (dateInitValue.value == '') {
    uni.showToast({
      title: '请选择随访日期！',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  if (visitSign == -1) {
    addVisitFrom.value.doctorId = visitStore.patient?.doctorId as any
    addVisitFrom.value.patientId = visitStore.patient?.id as any
    addVisitFrom.value.visitTime = dateInitValue.value as any
    addVisitFrom.value.visitWay = visitWay[selectWayIndex.value]
    addVisitFrom.value.visitSign = visitSign.toString() as any
    uni.showModal({
      content: '确认要新增预约吗？',
      success: async (res) => {
        if (res.confirm) {
          // 用户点击了确定按钮
          const res = await http<any>({
            url: '/visit/addVisit',
            data: addVisitFrom.value,
            method: 'POST',
          })
          console.log(res)
          if (res.code == 200) {
            uni.showToast({
              title: '新增预约成功！',
              icon: 'none',
              duration: 2000,
            })
            visitStore.setVisit(res.data)
            uni.redirectTo({ url: '/pages/index/visit/components/VisitDesc' })
          }
        } else if (res.cancel) {
          // 用户点击了取消按钮
          console.log('用户点击了取消按钮')
        }
      },
    })
    return
  }
  try {
    await formRef.value?.validate?.()
    addVisitFrom.value.doctorId = visitStore.patient?.doctorId as any
    addVisitFrom.value.patientId = visitStore.patient?.id as any
    addVisitFrom.value.visitTime = dateInitValue.value as any
    addVisitFrom.value.visitWay = visitWay[selectWayIndex.value]
    addVisitFrom.value.visitSign = visitSign.toString() as any
    addVisitFrom.value.healthTime = getTime()
    console.log(addVisitFrom.value)
    if (visitSign == 0) {
      uni.showModal({
        content: '确认要存为草稿吗？',
        success: async (res) => {
          if (res.confirm) {
            // 用户点击了确定按钮
            const res = await http<any>({
              url: '/visit/addVisit',
              data: addVisitFrom.value,
              method: 'POST',
            })
            console.log(res)
            if (res.code == 200) {
              uni.showToast({
                title: '保存草稿成功！',
                icon: 'none',
                duration: 2000,
              })
              visitStore.setVisit(res.data)
              uni.redirectTo({ url: '/pages/index/visit/components/VisitDesc' })
            }
          } else if (res.cancel) {
            // 用户点击了取消按钮
            console.log('用户点击了取消按钮')
          }
        },
      })
    } else if (visitSign == 1) {
      uni.showModal({
        content: '确认要完成随访吗？',
        success: async (res) => {
          if (res.confirm) {
            // 用户点击了确定按钮
            const res = await http<any>({
              url: '/visit/addVisit',
              data: addVisitFrom.value,
              method: 'POST',
            })
            console.log(res)
            if (res.code == 200) {
              uni.showToast({
                title: '新增随访成功！',
                icon: 'none',
                duration: 2000,
              })
              visitStore.setVisit(res.data)
              uni.redirectTo({ url: '/pages/index/visit/components/VisitDesc' })
            }
          } else if (res.cancel) {
            // 用户点击了取消按钮
            console.log('用户点击了取消按钮')
          }
        },
      })
    }
  } catch (error) {
    console.log(error)
  }
}

//获取患者症状列表
const getCrowdList = () => {
  console.log(visitStore.patient?.disease)
  http<any>({
    url: '/crowd/getCrowd?crowds=' + visitStore.patient?.disease,
    method: 'GET',
  }).then((res: any) => {
    console.log(res.data)
    crowdNameList.value = res.data.crowdNameList
    symptomList.value = res.data.symptomList
  })
}

//获取当前时间戳
const getTime = () => {
  // 创建一个Date对象来获取当前时间
  var now = new Date()
  // 从Date对象中提取年、月、日、小时、分钟和秒
  var year = now.getFullYear()
  var month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，需要加1并补零
  var day = String(now.getDate()).padStart(2, '0')
  var hours = String(now.getHours()).padStart(2, '0')
  var minutes = String(now.getMinutes()).padStart(2, '0')
  var seconds = String(now.getSeconds()).padStart(2, '0')

  // 将提取的值按指定格式拼接在一起
  var formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  return formattedDateTime
}

//是否显示随访方式列表
const changeShow = () => {
  showSelectWay.value = !showSelectWay.value
}

//改变随访方式
const chageVisitWay = (index: number) => {
  selectWayIndex.value = index
}

const symptomSet = ref<String[]>([])

//选择症状多选框
const selectCheckbox = (symptom: string) => {
  let newSet = new Set(symptomSet.value)
  if (newSet.has(symptom)) {
    newSet.delete(symptom)
  } else {
    newSet.add(symptom)
  }
  symptomSet.value = Array.from(newSet)
  console.log(symptomSet.value)
  addVisitFrom.value.symptoms = symptomSet.value.toString()
}

//监听症状选中数组长度
watch(
  () => symptomSet.value.length,
  (newVal, oldVal) => {
    console.log(newVal, oldVal)
    if (symptomSet.value.length == 0) {
      addVisitFrom.value.symptoms = '无症状'
    }
  },
)

onLoad(() => {
  getCrowdList()
  curruentTime.value = getTime()
  addVisitFrom.value.symptoms = '无症状'
})
</script>

<style lang="scss" scoped>
.addVisit-container {
  background-color: #f4f4f4;
  height: calc(100vh - 55rpx);
  padding: 5rpx 10rpx;
  .addVisit-wrapper {
    padding: 10rpx;
    background-color: #fff !important;
    border-radius: 5rpx;
    border: 1rpx solid #f4f4f4;
  }
}
.addVisit-firstrow {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  .addVisit-firstrow-box {
    display: flex;
    font-size: 12rpx;
    text-align: center;
    justify-content: center;
    align-items: center;
    .addVisit-text {
      color: #61666d;
    }
  }
}

.addVisit-secondrow {
  font-size: 12rpx;
  display: flex;
  flex-wrap: wrap;
  .checkbox-item {
    margin-right: 18rpx;
    margin-bottom: 10rpx;
  }
}

.addVisit-thridrow {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .addVisit-thridrow-box {
    font-size: 12rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 14rpx;
    margin-right: 19rpx;
    position: relative;
    .addVisit-text {
      color: #61666d;
    }
  }
}

.forms-error {
  position: absolute;
  width: 100%;
  top: 0rpx;
  left: 60rpx;
}

.addVisit-frouthrow {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .addVisit-frouthrow-box {
    font-size: 12rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 14rpx;
    margin-right: 19rpx;
    position: relative;
    .addVisit-text {
      color: #61666d;
    }
  }
}

.addVisit-active {
  color: #02abf3 !important;
}

.h-text {
  padding: 14rpx 0;
  font-size: 15rpx;
  color: #02abf3;
  font-weight: bold;
}

.addvisit-input {
  width: 90rpx;
  height: 22rpx;
  background-color: transparent;
  border: 0.5rpx solid #61666d;
  border-radius: 2rpx;
  padding: 0rpx 10rpx;
  margin-right: 5rpx;
}
.addVisit-crowdName-box {
  margin-top: 18rpx;
  font-size: 12rpx;
  .addVisit-crowdName-item {
    margin-right: 10rpx;
    background-color: transparent;
    border: 0.5rpx solid #61666d;
    border-radius: 2rpx;
    padding: 4rpx 10rpx;
    color: #61666d;
  }
}

.visit-way {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  border: 0.5rpx solid #61666d;
  border-radius: 2rpx;
  height: 20rpx;
  width: 60rpx;
  .visit-way-text {
    text-align: center;
    flex: 1;
  }
  .visit-way-after {
    width: 12rpx;
    height: 100%;
    background-color: #02abf3;
  }
}
.visit-way-list {
  position: absolute;
  top: 21rpx;
  right: 0rpx;
  width: 60rpx;
  height: 44rpx;
  padding: 2rpx 0;
  text-align: center;
  border-radius: 2rpx;
  background-color: #f4f4f4;
  .visit-way-item {
    height: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.visit-way-item-active {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 20rpx;
  color: #fff;
  background-color: #06d9f5;
  background: #fff radial-gradient(#06dbf5, #02abf3);
  border-radius: 5rpx;
}
</style>
